#!usr/bin/env python
# -*- coding:utf-8 _*

"""
@File : mpv2nii.py 
@Author : ljt
@Description: xx
@Time : 2021/6/9 11:57 
"""


import SimpleITK as sitk
import struct
import os
import numpy as np
import tkinter as tk
import os
from tkinter import Button
from tkinter.filedialog import askopenfilename, askdirectory

#初始化Tk()
myWindow = tk.Tk()

#设置标题
myWindow.title('医学图像格式转换软件v1.0')
#设置窗口大小
#设置窗口大小
width = 300
height = 300
#获取屏幕尺寸以计算布局参数，使窗口居屏幕中央
screenwidth = myWindow.winfo_screenwidth()
screenheight = myWindow.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
myWindow.geometry(alignstr)

def mpv2nii(path, target_path):
    size = os.path.getsize(path)
    binfile = open(path, 'rb')
    voxel_size = binfile.read(4)
    voxel_size = struct.unpack('f', voxel_size)
    d1 = binfile.read(4)
    d1 = struct.unpack('f', d1)
    d1 = int(d1[0])
    d2 = binfile.read(4)
    d2 = struct.unpack('f', d2)
    d2 = int(d2[0])
    d3 = binfile.read(4)
    d3 = struct.unpack('f', d3)
    d3 = int(d3[0])
    arr_data = np.ones((d1, d2, d3))
    size = os.path.getsize(path)
    print(size / 4)
    for i in range(arr_data.shape[2]):
        for j in range(arr_data.shape[1]):
            for k in range(arr_data.shape[0]):
                data = binfile.read(4)
                data = struct.unpack('f', data)
                # print(i,j,k)
                # print(struct.unpack('f', ground_data))
                arr_data[k,j,i] = data[0]

    nii_img = sitk.GetImageFromArray(arr_data)
    nii_img.SetSpacing((voxel_size[0], voxel_size[0], voxel_size[0]))
    sitk.WriteImage(nii_img, target_path + "/output.nii")
    print("转换完成！")
    print("原始文件：{}".format(path))
    print("转换后保存地址：{}".format(target_path + "/output.nii"))
    

def dcm2nii(path, target_path):
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(path)
    reader.SetFileNames(dicom_names)
    image2 = reader.Execute()
    sitk.WriteImage(image2, target_path + "/output.nii")  # 这里可以直接换成image2 这样就保存了原来的数据成了nii格式了。
    print("转换完成！")
    print("原始文件：{}".format(path))
    print("转换后保存地址：{}".format(target_path + "/output.nii"))


def convert1():
    default_dir = r'./'
    file_path= askopenfilename(title=u'选择文件',initialdir=(os.path.expanduser(default_dir)))
    target_dir = askdirectory(title=u'请选择保存位置')
    mpv2nii(file_path, target_dir)

def convert2():
    default_dir = r'./'
    file_path= askdirectory(title=u'选择dcm序列文件夹',initialdir=(os.path.expanduser(default_dir)))
    target_dir = askdirectory(title=u'请选择保存位置')
    dcm2nii(file_path, target_dir)




b1=Button(myWindow, text='mpv2nii',bg="gray", width=12, height=2,command=convert1)
b1.pack()


b2=Button(myWindow, text='dcm2nii',bg="gray", width=12, height=2,command=convert2)
b2.pack()


myWindow.mainloop()

